const asyncHooks = require('async_hooks');
const store = new Map();

const asyncHook = asyncHooks.createHook({
  init: (asyncId, _, triggerAsyncId) => {
    if (store.has(triggerAsyncId)) {
      store.set(asyncId, store.get(triggerAsyncId));
    }
  },
  destroy: (asyncId) => {
    if (store.has(asyncId)) {
      store.delete(asyncId);
    }
  },
});

asyncHook.enable();

function createRequestContext(data) {
  store.set(asyncHooks.executionAsyncId(), data);
  return data;
}

function getRequestContext() {
  return store.get(asyncHooks.executionAsyncId());
}

module.exports = {
  createRequestContext,
  getRequestContext,
};
